package cn.itcast.bos.web.action;

import java.util.concurrent.TimeUnit;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Controller;

import cn.itcast.bos.domain.constant.Constants;
import cn.itcast.bos.utils.MailUtils;
import cn.itcast.bos.utils.UUIDUtils;
import cn.itcast.bos.web.action.common.BaseAction;
import cn.itcast.crm.domain.Customer;

@Namespace("/")
@ParentPackage("struts-default")
@Scope("prototype")
@Controller
public class CustomerAction extends BaseAction<Customer> {
	private static final long serialVersionUID = 1L;
	@Autowired
	@Qualifier("jmsQueueTemplate")
	private JmsTemplate jmsTemplate;

	// 发送手机短信验证码
	@Action(value = "customer_sendSms")
	public void sendSms() throws Exception {
		// 生成6位数字的验证码
		String checkCode = RandomStringUtils.randomNumeric(6);
		// 将验证码输出
		System.out.println("验证码是：" + checkCode);
		// 将该手机号对应的验证码保存在session中
		ServletActionContext.getRequest().getSession().setAttribute(model.getTelephone(), checkCode);
		// 编写短信的内容
		final String content = "尊敬的" + model.getTelephone() + "您好,您本次注册(速运快递)的验证码是:" + checkCode + ",千万不要告诉别人哟!";
		// 调用activeMQ服务,向队列中发送一条信息,bos_sms就是队列名称
		jmsTemplate.send("bos_sms", new MessageCreator() {
			@Override
			public Message createMessage(Session session) throws JMSException {
				// 定义消息的格式
				MapMessage mapMessage = session.createMapMessage();
				mapMessage.setString("telephone", model.getTelephone());
				mapMessage.setString("content", content);
				return mapMessage;
			}
		});
	}

	// 完成注册功能
	private String checkcode;

	public void setCheckcode(String checkcode) {
		this.checkcode = checkcode;
	}

	@Autowired
	private RedisTemplate<String, String> redisTemlate;

	@Action(value = "customer_regist", results = {
			@Result(name = "success", location = "signup-success.html", type = "redirect"),
			@Result(name = "input", location = "signup.html", type = "redirect") })
	public String regist() {
		// 将session中的手机验证码取出来
		String sessioncheckcode = (String) ServletActionContext.getRequest().getSession()
				.getAttribute(model.getTelephone());
		// 判断 session中的验证码 和用户传过来的验证码是否一直
		if (sessioncheckcode == null || !sessioncheckcode.equals(checkcode)) {
			System.out.println("短信验证码不匹配");
			return INPUT;
		}
		// 调用webservice 保存客户信息
		WebClient.create(Constants.CRM_MANAGEMENT_URL + "/services/customerService/regist")
				.type(MediaType.APPLICATION_JSON).post(model);

		// 向客户提交过来的邮箱发送一封激活邮件
		// 生成激活码
		String activecode = UUIDUtils.getUUID();
		// 将激活码保存在redis中,并且有效时长为24小时
		redisTemlate.opsForValue().set(model.getTelephone(), activecode, 24, TimeUnit.HOURS);
		// 给用户发邮件
		String content = "尊敬的客户您好，请于24小时内，进行邮箱账户的绑定，点击下面地址完成绑定:<br/><a href='" + MailUtils.activeUrl + "?telephone="
				+ model.getTelephone() + "&activecode=" + activecode + "'>请猛戳这里完成激活</a>";
		MailUtils.sendMail("速运快递激活邮件", content, model.getEmail());
		return SUCCESS;
	}

	// 完成邮件的激活
	private String activecode;

	public void setActivecode(String activecode) {
		this.activecode = activecode;
	}

	@Action(value = "customer_activeMail")
	public void activeMail() throws Exception {
		// 解决response响应中文到页面乱码
		ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
		// 从redis中获取存储的邮件激活码
		String activecodeRedis = redisTemlate.opsForValue().get(model.getTelephone());
		// 判断激活码是否为空,或者激活码与用户传递过来的激活码是否相等
		if (activecodeRedis == null || !activecodeRedis.equals(activecode)) {
			ServletActionContext.getResponse().getWriter().println("激活码无效，请登录系统，重新绑定邮箱！");
		} else {
			// 通过手机号查找要激活的用户
			Customer customer = WebClient.create(Constants.CRM_MANAGEMENT_URL
					+ "/services/customerService/regist/findByTelephone/" + model.getTelephone())
					.accept(MediaType.APPLICATION_JSON).get(Customer.class);
			// 判断用户是否激活过
			if (customer.getType() == null || customer.getType() != 1) {
				// 没激活,就将customer的type值改为1
				WebClient.create(Constants.CRM_MANAGEMENT_URL + "/services/customerService/regist/updateType/"
						+ model.getTelephone()).put(null);
				ServletActionContext.getResponse().getWriter().println("邮箱绑定成功！");
			} else {
				ServletActionContext.getResponse().getWriter().println("邮箱已经绑过,请不要重复绑定！");
			}
			// 将redis里的激活码删除
			redisTemlate.delete(model.getTelephone());
		}
	}

	// 用户登录功能
	@Action(value = "customer_login", results = {
			@Result(name = "success", location = "index.html#/myhome", type = "redirect"),
			@Result(name = "error", location = "login.html", type = "redirect") })
	public String login() {
		Customer existCustomer = WebClient
				.create(Constants.CRM_MANAGEMENT_URL + "/services/customerService/login?telephone="
						+ model.getTelephone() + "&password=" + model.getPassword())
				.accept(MediaType.APPLICATION_JSON).get(Customer.class);
		if (existCustomer == null) {
			return ERROR;
		}
		// 将查询到的登录的用户保存在session域中
		ServletActionContext.getRequest().getSession().setAttribute("existCustomer", existCustomer);
		return SUCCESS;
	}

}
